/**
 * TimelineBuilder
 * 负责构建实体的时间轴（交易、通话、出行等）
 */
class TimelineBuilder {

    /**
     * 构建时间轴入口 (Facade)
     * @param {Object} knex 
     */
    static async build(knex) {
        await this.buildBankEvents(knex);
        await this.buildCallEvents(knex);
    }

    /**
     * 构建银行交易事件
     * @param {Object} knex 
     */
    static async buildBankEvents(knex) {
        const hasTable = await knex.schema.hasTable('bank_transactions');
        if (!hasTable) return;

        // 插入银行流水到 timeline
        // 核心字段映射:
        // identifier -> card_number
        // event_time -> transaction_time
        // event_type -> 'bank'
        // event_summary -> 摘要 (收/支 + 金额 + 对方)
        await knex.raw(`
            INSERT INTO profile_timeline (identifier, event_time, event_type, event_summary, location, source_table, source_id)
            SELECT 
                card_number, 
                transaction_time, 
                'bank', 
                CASE 
                    WHEN debit_credit_flag = '借' THEN '支出 ' || transaction_amount || ' (对方: ' || IFNULL(counterparty_name, '') || ')'
                    ELSE '收入 ' || transaction_amount || ' (对方: ' || IFNULL(counterparty_name, '') || ')'
                END,
                transaction_branch_name,
                'bank_transactions',
                id
            FROM bank_transactions
            WHERE card_number IS NOT NULL AND transaction_time IS NOT NULL
        `);

        console.log(`[TimelineBuilder] Built bank events`);
    }

    /**
     * 构建通话记录事件
     * @param {Object} knex 
     */
    static async buildCallEvents(knex) {
        const hasTable = await knex.schema.hasTable('call_records');
        if (!hasTable) return;

        // 插入通话记录到 timeline
        await knex.raw(`
            INSERT INTO profile_timeline (identifier, event_time, event_type, event_summary, location, source_table, source_id)
            SELECT 
                phone_number, 
                start_time, 
                'call', 
                '通话 (' || call_type || ') ' || duration || '秒 (对方: ' || other_number || ')',
                location,
                'call_records',
                id
            FROM call_records
            WHERE phone_number IS NOT NULL AND start_time IS NOT NULL
        `);

        console.log(`[TimelineBuilder] Built call events`);
    }
}

module.exports = TimelineBuilder;
